<template>
  <div class="pregnancy-view">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="handleAddNew" :icon="Plus" :disabled="!hasTableData">
          + 新增
        </el-button>
        <el-button type="success" @click="saveData" :icon="Document" :disabled="!hasAnyData">
          保存
        </el-button>
        <el-button @click="handleUndo" :icon="RefreshLeft" :disabled="!hasChanges">
          撤销
        </el-button>
        <el-button type="danger" @click="handleDelete" :icon="Delete" :disabled="!isEditMode">
          删除
        </el-button>
      </div>
      <div class="action-right">
        <el-icon class="action-icon">
          <Setting />
        </el-icon>
        <el-icon class="action-icon">
          <Printer />
        </el-icon>
      </div>
    </div>

    <!-- 头部表单区域 -->
    <div class="form-section">
      <div class="form-row">
        <div class="form-item">
          <label class="required">负责人</label>
          <el-select v-model="formData.responsibleFor" placeholder="请选择负责人" clearable>
            <el-option label="海绵宝宝" value="海绵宝宝" />
            <el-option label="派大星" value="派大星" />
            <el-option label="蟹老板" value="蟹老板" />
          </el-select>
        </div>
        <div class="form-item">
          <label class="required">妊检日期</label>
          <el-date-picker v-model="formData.mainPregnancyTime" type="date" placeholder="选择日期" format="YYYY/MM/DD"
            value-format="YYYY/MM/DD" />
        </div>
        <div class="form-item">
          <label>单据号</label>
          <el-input v-model="formData.documentNumber" readonly />
        </div>
        <div class="form-item">
          <label>流水号</label>
          <el-input v-model="formData.serialNumber" readonly />
        </div>
      </div>
    </div>

    <!-- 主数据表格区域 -->
    <div class="table-section">
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="*耳号" width="120">
          <template #default="{ row, $index }">
            <el-input v-model="row.pregnancySnowId" placeholder="请输入耳号"
              @blur="validateRequiredField(row, 'pregnancySnowId', $index)" />
          </template>
        </el-table-column>
        <el-table-column label="*妊检结果" width="220">
          <template #default="{ row, $index }">
            <el-select v-model="row.pregnancyResult" placeholder="请选择"
              @change="validateRequiredField(row, 'pregnancyResult', $index)">
              <el-option label="怀孕" value="怀孕" />
              <el-option label="未怀孕" value="未怀孕" />
              <el-option label="不确定" value="不确定" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="*妊检方式" width="220">
          <template #default="{ row, $index }">
            <el-select v-model="row.pregnancyMethod" placeholder="请选择"
              @change="validateRequiredField(row, 'pregnancyMethod', $index)">
              <el-option label="B超检查" value="B超检查" />
              <el-option label="血液检测" value="血液检测" />
              <el-option label="外部检查" value="外部检查" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="同胎数" width="200">
          <template #default="{ row }">
            <el-input-number v-model="row.pregnancySameNum" :min="0" :max="10" controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="妊娠天数" width="200">
          <template #default="{ row }">
            <el-input-number v-model="row.pregnancyDayNum" :min="0" :max="200" controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="当前栋舍" width="120">
          <template #default="{ row }">
            <el-input v-model="row.pregnancyPoultryhome" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="当前栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.pregnancyField" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="转入栋舍" width="120">
          <template #default="{ row }">
            <el-input v-model="row.pregnancyTransferHouse" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="转入栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.pregnancyTransfer" placeholder="请输入" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部操作和备注区域 -->
    <div class="footer-section">
      <div class="row-actions">
        <el-button type="primary" @click="handleAddRow" :icon="Plus">
          + 增行
        </el-button>
        <el-button type="danger" @click="handleDeleteRows" :icon="Delete">
          - 删行
        </el-button>
      </div>
      <div class="remarks-section">
        <label>备注</label>
        <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Document,
  RefreshLeft,
  Delete,
  Setting,
  Printer
} from '@element-plus/icons-vue'
import { Writes } from '@/Utils/axiosHelper'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()

// 接口类型定义
interface PregnancyRecord {
  pregnancyId: number
  pregnancySnowId: string
  pregnancyResult: string
  pregnancyMethod: string
  pregnancySameNum: number
  pregnancyDayNum: number
  pregnancyPoultryhome: string
  pregnancyField: string
  pregnancyTransferHouse: string
  pregnancyTransfer: string
  remarks: string
}


const formData = reactive({
  responsibleFor: '',
  mainPregnancyTime: '',
  documentNumber: '',
  serialNumber: '',
  remarks: ''
})

const tableData = ref<PregnancyRecord[]>([])
const selectedRows = ref<PregnancyRecord[]>([])
const isEditMode = ref(false)
const originalData = ref<any>(null)
// 计算属性
// 生成单据号和流水号
const generateDocumentNumbers = () => {
  const timestamp = Date.now()
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  // 单据号格式：PC + 年月日 + 时间戳后6位
  formData.documentNumber = `PC${year}${month}${day}${String(timestamp).slice(-6)}`

  // 流水号格式：SN + 时间戳
  formData.serialNumber = `SN${timestamp}`
}

const hasTableData = computed(() => tableData.value.length > 0)

// 检查是否有任何数据输入
const hasAnyData = computed(() => {
  // 检查表单是否有数据
  const hasFormData = formData.responsibleFor || formData.mainPregnancyTime

  // 检查表格是否有数据（至少一行包含非空字段）
  const hasTableData = tableData.value.some(row =>
    row.pregnancySnowId ||
    row.pregnancyResult ||
    row.pregnancyMethod ||
    row.pregnancySameNum > 0 ||
    row.pregnancyDayNum > 0 ||
    row.pregnancyPoultryhome ||
    row.pregnancyField ||
    row.pregnancyTransferHouse ||
    row.pregnancyTransfer ||
    row.remarks
  )

  return hasFormData || hasTableData
})

const hasChanges = computed(() => {
  if (!originalData.value) return false
  return JSON.stringify(formData) !== JSON.stringify(originalData.value.formData) ||
    JSON.stringify(tableData.value) !== JSON.stringify(originalData.value.tableData)
})

// 添加新行
const addNewRow = () => {
  const newRow: PregnancyRecord = {
    pregnancyId: 0,
    pregnancySnowId: '',
    pregnancyResult: '',
    pregnancyMethod: '',
    pregnancySameNum: 0,
    pregnancyDayNum: 0,
    pregnancyPoultryhome: '',
    pregnancyField: '',
    pregnancyTransferHouse: '',
    pregnancyTransfer: '',
    remarks: ''
  }
  tableData.value.push(newRow)
  saveOriginalData()
}

// 删除行
const deleteSelectedRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }

  const selectedIds = selectedRows.value.map(row => tableData.value.indexOf(row))
  tableData.value = tableData.value.filter((_, index) => !selectedIds.includes(index))
  selectedRows.value = []
  saveOriginalData()
  ElMessage.success(`已删除 ${selectedIds.length} 行数据`)
}

// 顶部操作栏方法
const handleAddNew = () => {
  ElMessageBox.confirm('确定要新增记录吗？当前未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetForm()
    ElMessage.success('已重置表单')
  }).catch(() => {
    // 用户取消
  })
}

// 保存数据到后端
const saveData = async () => {
  try {
    // 校验表单必填字段
    if (!formData.responsibleFor) {
      ElMessage.warning('请选择负责人');
      return;
    }

    if (!formData.mainPregnancyTime) {
      ElMessage.warning('请选择妊检日期');
      return;
    }

    // 校验表格数据
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('请至少添加一条妊检记录');
      return;
    }

    // 过滤并校验有效数据
    const validRows = tableData.value.filter(row =>
      row.pregnancySnowId &&
      row.pregnancyResult &&
      row.pregnancyMethod
    );

    if (validRows.length === 0) {
      ElMessage.warning('请至少填写一条完整的数据（耳号、妊检结果、妊检方式）');
      return;
    }

    // 转换日期格式：从 YYYY/MM/DD 转换为 ISO 格式
    let formattedDate = formData.mainPregnancyTime;
    if (formattedDate && formattedDate.includes('/')) {
      // 将 YYYY/MM/DD 转换为 YYYY-MM-DD
      formattedDate = formattedDate.replace(/\//g, '-');
      // 如果没有时间部分，添加默认时间
      if (!formattedDate.includes('T')) {
        formattedDate = `${formattedDate}T00:00:00`;
      }
    }

    const addPayload = {
      responsibleFor: formData.responsibleFor,
      mainPregnancyTime: formattedDate,
      documentNumber: formData.documentNumber,
      serialNumber: formData.serialNumber,
      pregnancysList: validRows.map(row => {
        return {
          pregnancySnowId: row.pregnancySnowId,
          pregnancyResult: row.pregnancyResult,
          pregnancyMethod: row.pregnancyMethod,
          pregnancySameNum: row.pregnancySameNum,
          pregnancyDayNum: row.pregnancyDayNum,
          pregnancyPoultryhome: row.pregnancyPoultryhome,
          pregnancyField: row.pregnancyField,
          pregnancyTransferhouse: row.pregnancyTransferHouse,
          pregnancyTransfer: row.pregnancyTransfer,
          remarks: row.remarks || ""
        }
      })
    };

    console.log('批量添加请求数据:', addPayload);
    const addRes = await Writes.post("Management/AddBatchPregnancys", addPayload);
    console.log('批量添加响应:', addRes);

    if (addRes.data.code == 100) {
      ElMessage.success(`批量添加成功，共添加${validRows.length}条记录`);
      router.push('/EwePregnancyList');
      // 添加成功后，更新表格中的数据为编辑模式
      validRows.forEach(row => {
        row.pregnancyId = Date.now(); // 临时ID，实际应该从响应中获取
      });
      // 保存成功后，更新原始数据以支持撤销功能
      saveOriginalData();
    } else {
      ElMessage.error(addRes.data.msg || '批量添加失败');
    }
  } catch (error: any) {
    console.error('批量添加失败', error);
    console.error('错误详情:', error.response?.data);
    ElMessage.error(error.response?.data?.msg || '批量添加失败');
  }
};


const handleUndo = () => {
  if (originalData.value) {
    Object.assign(formData, originalData.value.formData)
    tableData.value = [...(originalData.value.tableData || [])]
    ElMessage.success('已撤销更改')
  }
}

const handleDelete = () => {
  if (!isEditMode.value) {
    ElMessage.warning('请先保存记录')
    return
  }

  ElMessageBox.confirm('确定要删除当前记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // TODO: 调用后端删除接口
      // await deletePregnancyRecord()
      resetForm()
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('Delete error:', error)
    }
  }).catch(() => {
    // 用户取消
  })
}

// 表格操作方法
const handleAddRow = () => {
  addNewRow()
}

const handleDeleteRows = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有可删除的行')
    return
  }

  if (selectedRows.value.length > 0) {
    deleteSelectedRows()
  } else {
    // 如果没有选择行，默认删除最后一行
    tableData.value.pop()
    saveOriginalData()
    ElMessage.success('已删除最后一行')
  }
}

const handleSelectionChange = (selection: PregnancyRecord[]) => {
  selectedRows.value = selection || []
}

const validateRequiredField = (row: PregnancyRecord, field: keyof PregnancyRecord, index: number) => {
  if (!row[field]) {
    ElMessage.warning(`第 ${index + 1} 行${getFieldLabel(field)}不能为空`)
    return false
  }
  return true
}

const getFieldLabel = (field: keyof PregnancyRecord): string => {
  const labels: { [key: string]: string } = {
    pregnancySnowId: '耳号',
    pregnancyResult: '妊检结果',
    pregnancyMethod: '妊检方式'
  }
  return labels[field] || field
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    responsibleFor: '',
    mainPregnancyTime: '',
    documentNumber: '',
    serialNumber: '',
    remarks: ''
  })
  // 自动生成单据号和流水号
  generateDocumentNumbers()
  tableData.value = []
  selectedRows.value = []
  isEditMode.value = false
  originalData.value = null
  // 初始化一行数据
  addNewRow()
}

// 保存原始数据（用于撤销功能）
const saveOriginalData = () => {
  originalData.value = {
    formData: { ...formData },
    tableData: JSON.parse(JSON.stringify(tableData.value))
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 自动生成单据号和流水号
  generateDocumentNumbers()
  // 初始化一行数据
  addNewRow()
})
</script>

<style scoped>
.pregnancy-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 15px 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.action-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.action-right {
  display: flex;
  gap: 15px;
  align-items: center;
}

.action-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
  padding: 5px;
}

.action-icon:hover {
  color: #409eff;
}

/* 表单区域 */
.form-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  align-items: end;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item label.required::after {
  content: ' *';
  color: #f56c6c;
}

.form-item :deep(.el-input),
.form-item :deep(.el-select),
.form-item :deep(.el-date-editor) {
  width: 100%;
}

/* 表格区域 */
.table-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 底部区域 */
.footer-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.row-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.remarks-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.remarks-section label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.remarks-section :deep(.el-textarea) {
  width: 100%;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table td) {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

/* 表格行样式 */
:deep(.el-table .el-table__row) {
  height: 45px;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f8f9fa;
}

/* 表格单元格样式 */
:deep(.el-table .el-table__cell) {
  padding: 0 8px;
}

/* 按钮样式优化 */
.action-left :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
}

.row-actions :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }

  .action-left {
    flex-wrap: wrap;
    gap: 8px;
  }

  .action-right {
    gap: 10px;
  }

  .pregnancy-view {
    padding: 10px;
  }

  .action-bar,
  .form-section,
  .table-section,
  .footer-section {
    margin-bottom: 15px;
  }
}

/* 禁用状态样式 */
:deep(.el-button.is-disabled) {
  opacity: 0.5;
}
</style>
